package ph.com.gs3.formalistics.model.ldao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.LocalDataAccessObject;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

public class FilesLDAO extends LocalDataAccessObject {

	public FilesLDAO(Context context) {
		super(context);
	}

	public File storeImage(Bitmap image) {
		File pictureFile = getOutputMediaFile();
		if (pictureFile == null) {
			FLLogger.d(TAG, "Error creating media file, check storage permissions: ");// e.getMessage());
			return null;
		}
		try {
			FileOutputStream fos = new FileOutputStream(pictureFile);
			image.compress(Bitmap.CompressFormat.PNG, 90, fos);
			fos.close();
		} catch (FileNotFoundException e) {
			FLLogger.d(TAG, "File not found: " + e.getMessage());
		} catch (IOException e) {
			FLLogger.d(TAG, "Error accessing file: " + e.getMessage());
		}
		
		return pictureFile;
	}

	private File getOutputMediaFile() {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.
		File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
		        + "/Android/data/" + context.getPackageName() + "/Files");

		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
		File mediaFile;
		String mImageName = "IMG_" + timeStamp + ".jpg";
		mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
		return mediaFile;
	}

}
